package servlets.users;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UpdateUser extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private static final String MODIFYURLBASE = "http://localhost:8080/DatabaseRESTWebService/ModifyUser";
	
	protected void doPut(HttpServletRequest request, HttpServletResponse response) {
		String name, surname, email, password, cap, city, address, payPalEmail, idUser, answer, inputLine;
		BufferedReader reader;
		StringBuffer responseBuffer;
		
		name = request.getParameter("name");
		surname = request.getParameter("surname");
		email = request.getParameter("email");
		password = request.getParameter("password");
		cap = request.getParameter("cap");
		city = request.getParameter("city");
		address = request.getParameter("address");
		payPalEmail = request.getParameter("payPalEmail");
		idUser = request.getParameter("idUser");
		
		try {
			String url = MODIFYURLBASE + "?name="+ name + "&surname="+ surname + "&email="+ email + "&password="+ password + "&cap="+ cap + "&city="+ city + "&address="+ address + "&payPalEmail="+ payPalEmail + "&idUser="+ idUser;
			String cleanUrl = url.replace(" ", "%20");
			
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(cleanUrl).openConnection();
			httpConnection.setRequestMethod("PUT");
			httpConnection.setDoOutput(true); 
			httpConnection.setDoInput(true);
			httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			
			reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
	
			responseBuffer = new StringBuffer();
			
			while ((inputLine = reader.readLine()) != null) {
				responseBuffer.append(inputLine);
			}
			reader.close();
	
			answer = responseBuffer.toString();
			
			try {
				//write the result as JSon
				response.getWriter().write(answer);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			
		}
		
	}
}